package com.may.wlrj.util;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class PushCallback implements MqttCallback {
	//private static ObjectMapper mapper; 
    //private static com.fasterxml.jackson.databind.JsonNode rootNode;
	
	@Autowired
    private AmqpTemplate rabbitTemplate;

	public void connectionLost(Throwable cause) {  
        // 连接丢失后，一般在这里面进行重连  
        System.out.println("连接断开......");  
        MQTTUtil.stop();
        while(true) {
            try {
                Thread.sleep(30000);
                MQTTUtil.subscribe();
                break;
            }catch (InterruptedException e) {
                // terminate
            	continue;
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }  
  
	public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println("MQTT Rece:" + message.toString());
        try {
        	//this.rabbitTemplate.convertAndSend ("cloud", message.toString());
        }catch(Exception e) {
        	
        	e.printStackTrace();
        }
        
        /*try {
        	mapper = new ObjectMapper(); 
			rootNode = mapper.readTree(message.toString());
			String mac =rootNode.get("mac").asText();
			System.out.println("Parsed mac:" + mac);
		} catch (IOException e) {
			
		}*/		
    }

    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}
